import {
  getQualityDetectionInspectionPlanList,
  addQualityDetectionInspectionPlan,
  updateQualityDetectionInspectionPlan,
  deleteQualityDetectionInspectionPlan,
} from "@/api/basicData/qualityInspectionPlan.js";

export const myMethod = {
  // 切换条数
  handleSizeChange(val) {
    this.pageSize = val;
    this.currentPage = 1;
    this.getTableData();
  },
  // 切换页码
  handleCurrentChange(val) {
    this.currentPage = val;
    this.getTableData();
  },
  // 点击查询操作
  queryChange(val) {
    this.form = Object.assign(this.form, val);
    this.currentPage = 1;
    this.getTableData();
  },
  // 重置查询数据
  resetPage() {
    this.pageSize = 15;
    this.currentPage = 1;
    this.totalPage = 0;
    this.$refs.dataTableRef.tableData = [];
    this.form = {};
  },
  // 获取列表数据
  async getTableData() {
    this.$refs.dataTableRef.tableLoading = true;
    try {
      const { qualityDetectionInspectionPlanName, WorkOrderCode } = this.form;
      const params = {
        QualityDetectionInspectionPlanCode: WorkOrderCode || "", // 质量检验方案编码
        QualityDetectionInspectionPlanName: qualityDetectionInspectionPlanName || "", // 质检检验方案名称
        rows: this.pageSize,
        page: this.currentPage,
      };
      console.log(params);
      const res = await getQualityDetectionInspectionPlanList(params);
      if (res.status === 0) {
        this.$refs.dataTableRef.tableData = res.rows || [];
        console.log(this.$refs.dataTableRef.tableData);
        this.totalPage = res.total || 0;
      } else {
        this.$refs.dataTableRef.tableData = [];
        this.totalPage = 0;
        this.$message.error(res.msg || "查询失败");
      }
      this.$refs.dataTableRef.tableLoading = false;
    } catch (err) {
      this.$message.error(err.msg || "查询失败");
      this.$refs.dataTableRef.tableLoading = false;
    }
  },
  addChange() {
    this.addTitle = "添加质量检验方案";
    this.$refs.addDialogComRef.dialogVisible = true;
    this.$nextTick(() => {
      this.$refs.inspectionInfoRef.clearValidate();
      this.$refs.inspectionInfoRef2.clearValidate();
    });
    // 获取下拉框列表数据
    this.processData();
  },
  // 获取检验项目列表数据
  async getInspectionProjectList() {
    const params = {
      QualityDetectionProjectCode: "",
      QualityDetectionProjectName: "",
      rows: 1000,
      page: 1,
    };
    const query = new URLSearchParams(params).toString();
    const url = `/api/QualityDetection/GetQualityDetectionProjectList?${query}`;
    return this.http
      .get(url, {}, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  // 获取检验指标列表数据
  async getInspectionIndicatorsList() {
    const params = {
      QualityDetectionIndicatorId: "",
      QualityDetectionIndicatorCode: "",
      QualityDetectionIndicatorName: "",
      rows: 1000,
      page: 1,
    };
    const query = new URLSearchParams(params).toString();
    const url = `/api/QualityDetection/GetQualityDetectionIndicatorList?${query}`;
    return this.http
      .get(url, {}, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  async processData() {
    this.$refs.addDialogComRef.loading = true;
    try {
      const [data1, data2] = await Promise.all([
        this.getInspectionProjectList(),
        this.getInspectionIndicatorsList(),
      ]);
      this.inspectionProjectDataTemp = data1 ? JSON.parse(JSON.stringify(data1)) : [];
      this.inspectionIndicatorsDataTemp = data2 ? JSON.parse(JSON.stringify(data2)) : [];
      this.$refs.addDialogComRef.loading = false;
    } catch (error) {
      this.$refs.addDialogComRef.loading = false;
      console.error("获取数据失败:", error);
    }
  },
  // 增加行数据
  addRow() {
    let index = this.qualityDetectionInspectionPlanDetails.length;
    this.qualityDetectionInspectionPlanDetails.push({
      key: index,
      qualityDetectionProjectId: "",
      qualityDetectionIndicatorId: "",
    });
    console.log(this.qualityDetectionInspectionPlanDetails);
  },
  // 删除行数据
  handleDeleteRow(row) {
    let data = this.qualityDetectionInspectionPlanDetails;
    for (var i = 0; i < data.length; i++) {
      if (data[i].key == row.key) {
        data.splice(i, 1);
      }
    }
  },
  // 重置table行数据
  resetForm() {
    this.inspectionProjectDataTemp = [];
    this.inspectionIndicatorsDataTemp = [];
    let data = this.qualityDetectionInspectionPlanDetails;
    // 清空数据
    for (var i = 0; i < data.length; i++) {
      data[i].qualityDetectionProjectId = "";
      data[i].qualityDetectionIndicatorId = "";
    }
    // 如果全部删除 再初始化一条数据
    if(this.qualityDetectionInspectionPlanDetails.length === 0) {
      this.qualityDetectionInspectionPlanDetails = [{key: 0, qualityDetectionProjectId: null, qualityDetectionIndicatorId: null}]
    }
    // 保留一条
    this.qualityDetectionInspectionPlanDetails.splice(1)
    console.log('清空数据Table：', this.qualityDetectionInspectionPlanDetails);
  },
  // 清空弹框的数据
  closeChange() {
    this.inspectionInfo = {};
    this.resetForm();
    this.$refs.inspectionInfoRef.clearValidate();
    this.$refs.inspectionInfoRef2.clearValidate();
  },
  handleSelectChange(value, index) {
    console.log("选中的值:", value);
    console.log("索引:", index);
    // 重新选择需要清空检验指标
    this.qualityDetectionInspectionPlanDetails[index].qualityDetectionIndicatorId = null;
  },
  // 确认提交操作
  confirmChange() {
    this.$refs.inspectionInfoRef.validate((valid) => {
      if (valid) {
        if(this.qualityDetectionInspectionPlanDetails.length === 0) {
          this.$message.error('至少添加一行数据')
          return
        }
        this.$refs.inspectionInfoRef2.validate(async (valid2) => {
          if (valid2) {
            try {
              this.$refs.addDialogComRef.loading = true;
              const {
                qualityDetectionInspectionPlanCode,
                qualityDetectionInspectionPlanName,
                remark,
              } = this.inspectionInfo;
              const params = {
                qualityDetectionInspectionPlanCode: qualityDetectionInspectionPlanCode, // 质量检验方案编码
                qualityDetectionInspectionPlanName: qualityDetectionInspectionPlanName, // 质量检验方案
                qualityDetectionInspectionPlanDetails: this.qualityDetectionInspectionPlanDetails.map((item) => {
                  return {
                    qualityDetectionIndicatorId: item.qualityDetectionIndicatorId,
                    qualityDetectionProjectId: item.qualityDetectionProjectId,
                  };
                }), // 检验项目检验指标集合array
                remark: remark, // 描述
              };
              const isAdd =
                !this.inspectionInfo.qualityDetectionInspectionPlanId;
              const text = isAdd ? "添加" : "修改";
              if (!isAdd) {
                params.qualityDetectionInspectionPlanId =
                  this.inspectionInfo.qualityDetectionInspectionPlanId;
              }
              const apiName = isAdd
                ? addQualityDetectionInspectionPlan
                : updateQualityDetectionInspectionPlan;
              const result = await apiName(params);
              if (result.ok) {
                this.$message.success(text + "成功");
                this.$refs.addDialogComRef.dialogVisible = false;
                if(isAdd) this.currentPage = 1
                this.closeChange();
                this.getTableData();
              } else {
                this.$message.error((result.err && result.err.msg) || (text + "失败"));
              }
              this.$refs.addDialogComRef.loading = false;
            } catch (err) {
              this.$refs.addDialogComRef.loading = false;
              console.error(text + "数据异常:", err);
            }
          }
        });
      }
    });
  },
  detailChange(val) {
    this.updateChange(val);
  },
  updateChange(val) {
    this.addTitle = "修改质量检验方案";
    this.inspectionInfo = JSON.parse(JSON.stringify(val))	;
    this.qualityDetectionInspectionPlanDetails = this.inspectionInfo.qualityDetectionInspectionPlanDetails.map((item, index)=> {
      return {
        key: index,
        qualityDetectionProjectId: item.qualityDetectionProjectId,
        qualityDetectionIndicatorId: item.qualityDetectionIndicatorId
      }
    })
    this.$refs.addDialogComRef.dialogVisible = true;
    this.$nextTick(() => {
      this.$refs.inspectionInfoRef.clearValidate();
      this.$refs.inspectionInfoRef2.clearValidate();
    });
    // 获取下拉框列表数据
    this.processData();
  },
  async deleteChange(val) {
    // delNum用于切换页码
    const delNum = 1;
    const oldCurrentPage = this.currentPage;
    if (delNum) {
      const temp = Math.ceil(
        (this.totalPage - delNum ? this.totalPage - delNum : 1) / this.pageSize
      );
      if (this.currentPage > temp) {
        this.currentPage = temp;
      }
    }
    this.$refs.dataTableRef.tableLoading = true;
    try {
      const params = {
        id: val.qualityDetectionInspectionPlanId || "", // 质量检验方案id
      };
      const res = await deleteQualityDetectionInspectionPlan(params);
      if (res.ok) {
        this.$message.success("删除成功");
        this.getTableData();
      } else {
        this.currentPage = oldCurrentPage;
        this.$message.error((res.err&&res.err.msg) || "删除失败");
      }
      this.$refs.dataTableRef.tableLoading = false;
    } catch (err) {
      this.currentPage = oldCurrentPage;
      this.$message.error((err.err&&err.err.msg) || "删除失败");
      this.$refs.dataTableRef.tableLoading = false;
    }
  },
};
